package xj.graph2d;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import xj.util.xml.XMLUtil;

public class DrawShapeXMLBuilder {

  public DrawShapeXMLBuilder() {
    factory = DrawShapeFactory.getInstance();
  }

  public DrawShapeBase buildShape(Element node) {
    return buildShape(node, null);
  }

  public DrawShapeBase buildShape(Element node, String namespaceURI) {
    if (node != null) {
      String uri = node.getNamespaceURI();
      if (namespaceURI == null || namespaceURI.equals(uri)) {
	String name = node.getLocalName();
	String template = getTemplateName(node, namespaceURI);

	if (debug) {
	  System.out.println("DrawShapeXMLBuilder.buildShape(): namespaceURI=" + namespaceURI + 
			     " uri=" + uri + " name=" + name);
	}

	DrawShapeBase shape = null;
	if (template != null) {
	  shape = factory.makeShape(template, false);
	} 
	if (shape == null) { 
	  shape = factory.makeShape(name);
	}

	if (debug) {
	  System.out.println("DrawShapeXMLBuilder.buildShape(): shape=" + shape);
	}

	if (shape != null) {
	  shape.setAttrFromXML(node, namespaceURI);
	  return shape;
	}
      }
    }
    return null;
  }

  static protected String getTemplateName(Element node, String namespaceURI) {
    if (node != null) {
      NodeList nodes = node.getChildNodes();
      if (nodes != null) {
	int n = nodes.getLength();
	for (int i = 0; i < n; i++) {
	  Node cnode = nodes.item(i);
	  if (cnode.getNodeType() == Node.ELEMENT_NODE) {
	    Element e = (Element) cnode;
	    String uri = e.getNamespaceURI();
	    if (namespaceURI == null || namespaceURI.equals(uri)) {
	      String name = e.getLocalName();
	      if ("Template".equals(name)) {
		return XMLUtil.getTextChildNodeValue(e);
	      }
	    }
	  }
	}
      }
    }
    return null;
  }

  static protected DrawShapeFactory factory;

  static protected final boolean debug = false;

}
